#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
PostgreSQL服务模块
提供服务管理功能：启动、停止、重启、重载
"""

from ...core.utils import logger, run_command, get_service_name

class PostgresqlService:
    """PostgreSQL服务管理类"""
    
    def status(self):
        """检查PostgreSQL状态"""
        service_name = get_service_name(self.pg_version)
        logger.info("正在检查PostgreSQL状态")
        
        try:
            run_command(["sudo", "systemctl", "status", service_name])
        except Exception as e:
            logger.error(f"获取PostgreSQL状态时出错: {e}")
    
    def start(self):
        """启动PostgreSQL服务"""
        service_name = get_service_name(self.pg_version)
        logger.info("正在启动PostgreSQL")
        
        try:
            run_command(["sudo", "systemctl", "start", service_name])
            logger.info("PostgreSQL已启动")
        except Exception as e:
            logger.error(f"启动PostgreSQL时出错: {e}")
    
    def stop(self):
        """停止PostgreSQL服务"""
        service_name = get_service_name(self.pg_version)
        logger.info("正在停止PostgreSQL")
        
        try:
            run_command(["sudo", "systemctl", "stop", service_name])
            logger.info("PostgreSQL已停止")
        except Exception as e:
            logger.error(f"停止PostgreSQL时出错: {e}")
    
    def restart(self):
        """重启PostgreSQL服务"""
        service_name = get_service_name(self.pg_version)
        logger.info("正在重启PostgreSQL")
        
        try:
            run_command(["sudo", "systemctl", "restart", service_name])
            logger.info("PostgreSQL已重启")
        except Exception as e:
            logger.error(f"重启PostgreSQL时出错: {e}")
    
    def reload(self):
        """重新加载PostgreSQL配置"""
        service_name = get_service_name(self.pg_version)
        logger.info("正在重新加载PostgreSQL配置")
        
        try:
            run_command(["sudo", "systemctl", "reload", service_name])
            logger.info("PostgreSQL配置已重新加载")
        except Exception as e:
            logger.error(f"重新加载PostgreSQL配置时出错: {e}")
    
    def show_config(self):
        """显示PostgreSQL配置信息"""
        if not self.pg_version:
            logger.warning("未检测到PostgreSQL，无法显示配置信息")
            return
            
        logger.info(f"PostgreSQL版本: {self.pg_version}")
        logger.info(f"默认数据目录: /var/lib/postgresql/{self.pg_version}/main")
        logger.info(f"默认配置目录: /etc/postgresql/{self.pg_version}/main")
        logger.info(f"默认系统服务: {get_service_name(self.pg_version)}")
    
    def show_connections(self):
        """显示当前活动的数据库连接"""
        logger.info("当前活动的数据库连接:")
        
        try:
            run_command([
                "sudo", "-u", "postgres", "psql", 
                "-c", "\\x", 
                "-c", "SELECT * FROM pg_stat_activity;"
            ])
        except Exception as e:
            logger.error(f"获取数据库连接信息时出错: {e}") 